﻿package com.passioneffect.parser {
	import com.passioneffect.parser.IXMLParser;	

	/**
	 * @author Passion Effect
	 */
	public class ListXMLParser implements IXMLParser {
		public function parse(xml : XML) : Array {
			var arr : Array = [];
			var list : XMLList = xml.children();
			var item : XML;
			var prefix : Object = {};
			var defaultValue : Object = {};
			
			for each(var pre:XML in xml.@*) {
				var n : String = String(pre.name());
				if(n.indexOf("_default") != -1) {
					//default
					defaultValue[n] = pre.toXMLString();
				}else {
					//prefix
					prefix[n] = pre.toXMLString();
				}
			}
			
			for each(item in list) {
				var obj : Object = {};
				var atts : XMLList = item.children();
				var att : XML;
				var pre_ : String;
				var attName : String;
				var n2 : String;
				
				if(item.@id != undefined)
				obj.id = item.attribute("id");
				
				//set defaults first, att or element also same.
				for(n2 in defaultValue) {
					attName = n2.substr(0, n2.indexOf("_default") == -1 ? 0 : n2.indexOf("_default"));
					pre_ = prefix[attName + "_prefix"] || "";
					obj[attName] = pre_ + defaultValue[n2];
				}
				
				for each(att in atts) {
					pre_ = prefix[att.name() + "_prefix"] || "";
					obj[att.name()] = pre_ + att;
					
					//attributes of attribute
					for each(var i:XML in att.@*) {
						attName = att.name() + "@" + i.name();
						pre_ = prefix[attName + "_prefix"] || "";
						obj[attName] = pre_ + i;
					}
				}
				
				//if(obj.id==2)trace(obj.image);
				arr.push(obj);
			}
			return arr;
		}			
	}
}
